import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_plugin_demo2/flutter_plugin_demo2.dart';
import 'package:flutter_plugin_demo2_example/utils/screen_utils.dart';


class AllMainPage extends StatelessWidget {
  const AllMainPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}


class MoreParamsPage extends StatefulWidget {
  MoreParamsPage({Key? key}) : super(key: key);

  @override
  State<MoreParamsPage> createState() => _MoreParamsPageState();
}

class _MoreParamsPageState extends State<MoreParamsPage> {
  String? _paramStr = "";
  int? type = 1;
  TextEditingController firstEC = TextEditingController();
  FocusNode firstNode = FocusNode();

  static const EventChannel? _eventChannel = EventChannel("flutter_show_alert/event");
  StreamSubscription<dynamic>? _streamSubscription;

  // 计算乘积响应
  int? productCount = 0;

  // 当前音量为
  double? nowVoice = 0.0;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // FlutterPluginDemo2();
    // 方法2：在需要调用的地方设置监听(各自派发)
    _streamSubscription =  _eventChannel?.receiveBroadcastStream().listen((event) {
      final Map<dynamic,dynamic> map = event;
      String? key = map["key"];
      // int? value = map["value"];
      print("handle on ---$key---${map["value"]}");
      if(map["key"] == "changeVoice"){
        setState(() {
          nowVoice = map["value"];
        });
      }
      else if(map["key"] == "getCount") {
        setState(() {
                productCount = map["value"];
              });
      }
    },onError: errorEventListen,onDone:doneEventListen,) as StreamSubscription;



    // FlutterPluginDemo2.listener((args, args2) {
    //   print("args=$args-----args2=$args2");
    //   if(args == "changeVoice"){
    //
    //   }
    //   else if(args == "getCount") {
    //     setState(() {
    //       productCount = args2;
    //     });
    //   }
    //   setState(() {
    //
    //   });
    // });
  }

  errorEventListen(Object obj) {
    final Object e = obj;
    print("错误打印为------$obj");
    throw e;
  }

  doneEventListen() {
    print("flutter响应完成------");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("flutter和原生传参"),
      ),
      body: Container(
        width: ScreenUtils.getScreeenWidth(context),
        height: ScreenUtils.getScreeenHeidth(context),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("传参示例："),
              Container(
                padding: const EdgeInsets.all(20),

                child: Row(
                  children: [

                    const SizedBox(width: 10,),
                    Expanded(child: Container(
                      width: ScreenUtils.getScreeenWidth(context) * 0.5,
                      child: TextField(
                        controller: firstEC,
                        focusNode: firstNode,
                        keyboardType: TextInputType.number,
                        style:
                        const TextStyle(fontSize: 13.0, color: Colors.black),
                        decoration: const InputDecoration(
                          border: InputBorder.none,
                          hintText: "请输入数字",
                          hintStyle:
                          TextStyle(fontSize: 13.0, color: Colors.grey),
                        ),
                        onChanged: (value) {
                          setState(() {

                          });
                        },
                        // onSubmitted: (value) {
                        //   debugPrint("value = $value");
                        //
                        // },
                      ),
                    )),
                  ],
                ),
              ),
              const SizedBox(width: 10,),
              Text("flutter - 原输入值为:" + firstEC.text),
              Text(_paramStr!),

              InkWell(
                onTap: () async {
                  debugPrint("调用原生");
                  if(firstEC.text.isNotEmpty){
                    type = int.parse(firstEC.text);
                    sendParamsToOriginal();
                    firstNode.unfocus();
                  }

                },
                child: Container(
                  padding: const EdgeInsets.all(8),
                  color: Colors.blue,
                  child: Text(
                    "调用原生",
                  ),
                ),
              ),
              const Divider(),
              Text("flutter响应示例："  + (productCount != 0 ? "--输入值翻倍为" : "") + productCount.toString()),
              Text("flutter响应原生音量：" + nowVoice.toString()),
              InkWell(
                onTap: () async {
                  debugPrint("响应原生");
                  if(firstEC.text.isNotEmpty){
                    type = int.parse(firstEC.text);
                    await FlutterPluginDemo2.sendOriginalToHandle("传给原生",type!) ?? "0";
                    firstNode.unfocus();
                  }
                },
                child: Container(
                  padding: const EdgeInsets.all(8),
                  color: Colors.blue,
                  child: Text(
                    "响应原生",
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> sendParamsToOriginal() async {
    String originalStr;

    try {
      originalStr = await FlutterPluginDemo2.sendParamsToOriginal(type!,"传给原生") ?? "0";
    } on PlatformException {
      originalStr = "0";
    }
    if (!mounted) return;

    setState(() {
      _paramStr = originalStr;
    });
  }
}
